package com.ydsungan.controller;

import com.ydsungan.common.DateUtils;
import com.ydsungan.common.IpUtil;
import com.ydsungan.common.JSONResult;
import com.ydsungan.dao.PracticeMapper;
import com.ydsungan.pojo.*;
import com.ydsungan.service.BookService;
import com.ydsungan.service.QuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping(path = "/book")
@Api(value = "书本相关",tags = {"与书本相关的接口"})
@Slf4j
@CrossOrigin
public class BookController extends BasicController{
    @Autowired
    private BookService bookService;

    @Autowired
    private QuestionService questionService;

    @ApiOperation(value="添加书本",notes = "系统后台管理调用此接口")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JSONResult addBook(@RequestBody Book book) throws Exception{
        Book newbook = new Book();
        newbook.setBookName("肖秀荣考研1000题");
        bookService.addBook(newbook);
        return JSONResult.ok();
    }

    @ApiOperation(value="列举书本",notes = "按热度递减查出所有题库")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public JSONResult selectBook(HttpServletRequest request) throws Exception{

        BookExample bookExample = new BookExample();
        List<Book> list = bookService.selectBook(bookExample);

        return JSONResult.ok(list);
    }

    @ApiOperation(value="列举正在使用的书本",notes = "首页显示正在使用的书")
    @RequestMapping(value = "/using", method = RequestMethod.GET)
    public JSONResult selectUsingBook(String openId) throws Exception{

        List<Book> bookList = bookService.selectUsingBook(openId);


        List<String> jsonObjectList = new ArrayList<>();
        for(int i = 0; i < bookList.size(); ++i){


            QuestionExample questionExample = new QuestionExample();
            QuestionExample.Criteria questionCriteria = questionExample.createCriteria();
            questionCriteria.andBookIdEqualTo(bookList.get(i).getId());
            int total = (int)questionService.countQuestionByChapterId(questionExample);


            PracticeExample practiceExample = new PracticeExample();
            PracticeExample.Criteria practiceCriteria = practiceExample.createCriteria();
            practiceCriteria.andUserIdEqualTo(openId);
            practiceCriteria.andBookIdEqualTo(bookList.get(i).getId());
            int totalPracticeNum =  (int)bookService.countPracticeByOpenid(practiceExample);
            practiceCriteria.andIsRightEqualTo(1);
            int totalRightNum =  (int)bookService.countPracticeByOpenid(practiceExample);
            int percent = 0;
            int rate = 0;
            DecimalFormat decimalFormat = new DecimalFormat(".00");
            if(total != 0){
                String percentString = decimalFormat.format((float)totalPracticeNum/total);
                percent = (int)(Double.parseDouble(percentString) * 100);
            }
            if(totalPracticeNum != 0) {
                String rateString = decimalFormat.format((float) totalRightNum / totalPracticeNum);
                rate = (int) (Double.parseDouble(rateString) * 100);
            }

            JSONObject json = new JSONObject();
            json.put("bookId", bookList.get(i).getId());
            json.put("abbr",  bookList.get(i).getAbbr());
            json.put("bookName", bookList.get(i).getBookName());
            json.put("authorAndPress", bookList.get(i).getAuthor() + " / " + bookList.get(i).getPress());
            json.put("total", total);
            json.put("totalPracticeNum", totalPracticeNum);
            json.put("percent",percent);
            json.put("coverImg", bookList.get(i).getCoverImg());
            json.put("rate",rate);
            jsonObjectList.add(json.toString());
        }
        return JSONResult.ok(jsonObjectList);
    }

    @ApiOperation(value="考研倒计时",notes = "计算日期差")
    @RequestMapping(value = "/days", method = RequestMethod.GET)
    public JSONResult getCountDownNum() throws Exception{

        String target = redis.get("kaoyandate");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date targetDate = df.parse(target);
        int days = DateUtils.daysBetween(targetDate, new Date());


        return JSONResult.ok(days);
    }


    @ApiOperation(value="今天做题详情",notes = "首页卡片的信息")
    @RequestMapping(value = "/card", method = RequestMethod.GET)
    public JSONResult showCard(String openId) throws Exception{

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String today = df.format(new Date());
        String todayStart = today + " 00:00:00";
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
            dateTime = df2.parse(todayStart);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        StatisticsExample statisticsExample = new StatisticsExample();
        StatisticsExample.Criteria criteria1 = statisticsExample.createCriteria();
        criteria1.andUserIdEqualTo(openId);
        criteria1.andCreateTimeBetween(dateTime, new Date());
        List<Statistics> statisticsList = bookService.listStatistics(statisticsExample);
        if(statisticsList.size() == 0){
            Statistics statistics = new Statistics();
            statistics.setUserId(openId);
            statistics.setCreateTime(new Date());
            bookService.addLoginRecord(statistics);
        }

        StatisticsExample statisticsExample2 = new StatisticsExample();
        StatisticsExample.Criteria criteria2 = statisticsExample2.createCriteria();
        criteria2.andUserIdEqualTo(openId);
        List<Statistics> statisticsList2 = bookService.listStatistics(statisticsExample2);
        int continuedDays = 1;
        if(statisticsList2.size() > 1) {
            for (int i = statisticsList2.size() - 2; i >= 0; --i) {
                int difference = statisticsList2.size() - 1 - i;
                Date yesterday = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * difference);
                String yesterdayString = df.format(yesterday);
                String createTime = df.format(statisticsList2.get(i).getCreateTime());
                if(yesterdayString.equals(createTime)){
                    continuedDays += 1;
                }else{
                    break;
                }
            }
        }



        PracticeExample practiceExample = new PracticeExample();
        PracticeExample.Criteria criteria = practiceExample.createCriteria();
        criteria.andUserIdEqualTo(openId);
        criteria.andCreateTimeBetween(dateTime,new Date());
        int todayPracticeNum =  (int)bookService.countPracticeByOpenid(practiceExample);
        criteria.andIsRightEqualTo(1);
        int todayRightNum =  (int)bookService.countPracticeByOpenid(practiceExample);
        int rate = 0;
        if(todayPracticeNum != 0){
            DecimalFormat decimalFormat = new DecimalFormat(".00");
            String rateString = decimalFormat.format((float)todayRightNum/todayPracticeNum);
            rate = (int)(Double.parseDouble(rateString) * 100);
        }

        //获取排行榜
        //昨天-1,前天-2,-3,-4,-5,-6
        int rank = bookService.getRank(openId);

        JSONObject cardInfo = new JSONObject();
        cardInfo.put("todayPracticeNum", todayPracticeNum);
        cardInfo.put("rate", rate);
        cardInfo.put("rank",rank);
        cardInfo.put("continuedDays",continuedDays);
        return JSONResult.ok(cardInfo.toString());
    }

    @ApiOperation(value="列举书本的目录",notes = "根据书本的id查处书本的目录")
    @RequestMapping(value = "/listcatalog", method = RequestMethod.GET)
    public JSONResult listCatalog(String bookId, String id) throws Exception{

        ChapterExample chapterExample = new ChapterExample();
        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        criteria.andBookIdEqualTo(Integer.parseInt(bookId));
        List<Chapter> list = bookService.listCatalog(chapterExample);
        List<ChapterVO> chapterVOList = new ArrayList<ChapterVO>();

        //分别查处每个chapterId对应的题目数量
        for(int i = 0; i < list.size(); ++i){
            QuestionExample questionExample = new QuestionExample();
            QuestionExample.Criteria criteria1 = questionExample.createCriteria();
            criteria1.andChapterIdEqualTo(list.get(i).getId());
            int chapterSize = (int)questionService.countQuestionByChapterId(questionExample);
            ChapterVO chapterVO = new ChapterVO();
            BeanUtils.copyProperties(list.get(i), chapterVO);
            chapterVO.setChapterSize(chapterSize);

            PracticeExample practiceExample = new PracticeExample();
            PracticeExample.Criteria criteria2 = practiceExample.createCriteria();
            criteria2.andChapterIdEqualTo(list.get(i).getId());
            criteria2.andUserIdEqualTo(id);
            int practiceSize = (int)questionService.countPracticeByChapterId(practiceExample);
            chapterVO.setPracticeSize(practiceSize);
            chapterVOList.add(chapterVO);
        }

        return JSONResult.ok(chapterVOList);


    }

    @ApiOperation(value="题库详情",notes = "后台管理接口，显示题库的详情")
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public JSONResult getBookDetail(String bookId) throws Exception{

        return JSONResult.ok(bookService.getBookDetail(bookId));
    }


}
